<template>
  <el-dialog
    v-model="visible"
    title="关联设置"
    width="600px"
    :before-close="handleClose"
  >
    <div class="relate-content">
      <!-- 依赖组件选择 -->
      <div class="section">
        <h4>选择依赖组件</h4>
        <el-select
          v-model="selectedDependentComponent"
          placeholder="请选择依赖的组件"
          style="width: 100%"
          clearable
          @change="handleDependentComponentChange"
        >
          <el-option
            v-for="component in availableComponents"
            :key="component.id"
            :label="getComponentLabel(component)"
            :value="component.id"
          />
        </el-select>
      </div>

      <!-- 关联规则配置表格 -->
      <div class="section" v-if="selectedDependentComponent && currentComponentOptions.length > 0">
        <h4>关联规则配置</h4>
        <el-table :data="dependentComponentOptions" border style="width: 100%">
          <el-table-column prop="label" label="依赖组件值" width="200" />
          <el-table-column label="当前组件选项">
            <template #default="{ row }">
              <div class="tag-container">
                <el-tag
                  v-for="option in currentComponentOptions"
                  :key="option.value"
                  :type="isTagSelected(row.value, option.value) ? undefined : 'info'"
                  :effect="isTagSelected(row.value, option.value) ? 'dark' : 'plain'"
                  class="tag-item"
                  @click="toggleTag(row.value, option)"
                >
                  {{ option.label }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 启用关联功能 -->
      <div class="section">
        <el-checkbox v-model="localConfig.enabled">启用关联功能</el-checkbox>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import type { RelateConfig, CanvasComponent, Option } from "../types";

interface Props {
  modelValue: boolean;
  relateConfig: RelateConfig;
  componentOptions: Option[];
  allComponents: CanvasComponent[];
  currentComponentId: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  confirm: [config: RelateConfig];
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});


// 选中的依赖组件ID
const selectedDependentComponent = ref<string>('');

// 当前组件的选项
const currentComponentOptions = computed(() => {
  return props.componentOptions || [];
});


const localConfig = ref<RelateConfig>({
  enabled: false,
  dependentComponentId: '',
  currentComponentId: '',
  currentComponentOptions: [],
  rules: [],
});

// 递归获取所有子组件（用于grid组件）
const getAllChildComponents = (component: CanvasComponent): CanvasComponent[] => {
  if (!component.children || component.children.length === 0) return [];
  
  let children: CanvasComponent[] = [];
  for (const child of component.children) {
    children.push(child);
    children = [...children, ...getAllChildComponents(child)];
  }
  return children;
};

// 可用的组件列表（排除当前组件）
const availableComponents = computed(() => {
  const components: CanvasComponent[] = [];
  
  props.allComponents.forEach(comp => {
    // 排除当前组件
    if (comp.id === props.currentComponentId) return;
    
    // 如果组件有options，直接添加
    if (comp.props.options?.length > 0) {
      components.push(comp);
    }
    
    // 如果是grid组件，递归添加子组件
    if (comp.type === 'grid' && comp.children?.length) {
      const childComponents = getAllChildComponents(comp);
      childComponents.forEach(child => {
        if (child.props.options?.length > 0 && child.id !== props.currentComponentId) {
          components.push(child);
        }
      });
    }
  });
  
  return components;
});

// // 递归获取组件及其子组件的选项
// const getComponentOptions = (component: CanvasComponent): Option[] => {
//   let options: Option[] = [];
  
//   // 如果组件自身有 options 属性，则添加
//   if (component.props.options?.length > 0) {
//     options = [...component.props.options];
//   }
  
//   // 如果是 grid 组件且有子组件，则递归获取子组件的选项
//   if (component.type === 'grid' && component.children?.length) {
//     component.children.forEach(child => {
//       const childOptions = getComponentOptions(child);
//       if (childOptions.length > 0) {
//         options = [...options, ...childOptions];
//       }
//     });
//   }
  
//   return options;
// };

// 依赖组件的选项
const dependentComponentOptions = computed(() => {
  // if (!selectedDependentComponent.value) return [];
  // const component = props.allComponents.find(comp => comp.id === selectedDependentComponent.value);
  // if (!component) return [];
  
  // return getComponentOptions(component);
  const options = availableComponents.value.find(comp => comp.id === selectedDependentComponent.value)?.props.options || []
  return options;
});

// 生成组件显示标签
const getComponentLabel = (component: CanvasComponent): string => {
  return `${component.props.label} (${component.props.field})`;
};

// 处理依赖组件变化
const handleDependentComponentChange = (val: string) => {
  // 清空现有规则
  localConfig.value.rules = [];
  localConfig.value.dependentComponentId = val;
  localConfig.value.currentComponentId = props.currentComponentId;
  // 为当前组件的每个选项创建规则
  dependentComponentOptions.value.forEach((option: { value: string; label: string }) => {
    localConfig.value.rules.push({
      currentOptionValue: option.value,
      currentOptionLabel: option.label,
      dependentOptions: []
    });
  });
};

// 检查标签是否被选中
const isTagSelected = (currentOptionValue: string, dependentValue: string): boolean => {
  const rule = localConfig.value.rules.find(r => 
    r.currentOptionValue === currentOptionValue
  );
  return rule ? rule.dependentOptions.some((item) => item.value === dependentValue) : false;
};

// 切换标签选中状态
const toggleTag = (currentOptionValue: string, options: Option) => {
  const rule = localConfig.value.rules.find(r => 
    r.currentOptionValue === currentOptionValue
  );
  
  if (rule) {
    const index = rule.dependentOptions.findIndex((item) => item.value === options.value);
    if (index > -1) {
      rule.dependentOptions.splice(index, 1);
    } else {
      rule.dependentOptions.push(options);
    }
  }
};

// 监听props变化，初始化本地配置
watch(() => props.relateConfig, (newConfig) => {
  if (newConfig) {
    localConfig.value = { ...newConfig };
    // 如果有现有规则，设置选中的依赖组件
    if (newConfig.rules.length > 0) {
      selectedDependentComponent.value = newConfig.dependentComponentId;
    }
  }
}, { immediate: true });

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
  selectedDependentComponent.value = '';
};

// 确认设置
const handleConfirm = () => {
  localConfig.value.currentComponentOptions = currentComponentOptions.value;
  emit("confirm", localConfig.value);
  visible.value = false;
};
</script>

<style scoped lang="scss">
.relate-content {
  .section {
    margin-bottom: 20px;
    
    h4 {
      margin: 0 0 12px 0;
      color: #606266;
      font-size: 14px;
      font-weight: 600;
    }
  }
  
  .tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .tag-item {
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: scale(1.05);
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
